package org.example.controller;


import lombok.RequiredArgsConstructor;
import org.example.domain.ResponseResult;
import org.example.domain.entity.RoleMenu;
import org.example.service.RoleMenuService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/roleMenu")
@RequiredArgsConstructor
public class RoleMenuController {

    private final RoleMenuService roleMenuService;

    @GetMapping("/getMenusByRoleId/{id}")
    public ResponseResult getMenusByRoleId(@PathVariable Integer id){

        List<RoleMenu> roleMenuList = roleMenuService.getMenusByRoleId(id);
        List<Integer> menus = roleMenuList.stream().map(new Function<RoleMenu, Integer>() {
            @Override
            public Integer apply(RoleMenu roleMenu) {
                return roleMenu.getMenuId();
            }
        }).collect(Collectors.toList());
        return ResponseResult.okResult(menus);
    }

    @PostMapping("/updateRoleMenu/{id}")
    public ResponseResult updateRoleMenu(@PathVariable Integer id,@RequestBody Integer[] menusId){

        roleMenuService.deleteByRoleId(id);

        List<RoleMenu> roleMenuList = new ArrayList<>();
        for(int i=0;i<menusId.length;i++){
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menusId[i]);
            roleMenu.setRoleId(id);
            roleMenuList.add(roleMenu);
        }
       return ResponseResult.okResult(roleMenuService.saveBatch(roleMenuList));
    }

}
